#include						"Processor.h"
#include						<iostream>
#include						"IServerModule.h"
#include						"ModuleCall.h"
#include						"ModuleServer.h"
#include						"ConnectionManager.h"


Processor::Processor() : _conn(NULL)
{
	_protocol[SERVER] = new ModuleServer(*this);
	_protocol[CALL] = new ModuleCall(*this);
	time.start();
}

Processor::~Processor()
{
	for (std::map<Protocol , IServerModule *>::iterator it = _protocol.begin(); it != _protocol.end(); ++it)
		delete it->second;
}

void							Processor::update()
{

}

std::string						Processor::getIp(unsigned int ip) const
{
	return _conn->getIp(ip);
}

void							Processor::processOrder(IOrder *order)
{
	IServerModule		*plugin = NULL;
	Protocol	*proto = (Protocol*)order->getData(sizeof(Protocol));

	if (proto == NULL)
	{
		delete order;
		return;
	}
	std::cout << "Proto : " << *proto << std::endl;
	if (_protocol.find(*proto) != _protocol.end())
		plugin = _protocol[*proto];
	if (plugin != NULL)
		plugin->takeOrder(order, *proto);
	else
		delete order;
}

void							Processor::operator()(std::vector<byte> *order, unsigned short id)
{
	IOrder						*neworder = new Order;
	std::cout << "received order" << std::endl;
	neworder->setData(order);
	neworder->setSenderId(id);
	processOrder(neworder);
}

void							Processor::sendOrder(IOrder *order, unsigned int id)
{
	_conn->SendOrderToId(order, id);
}

void							Processor::setConn(ConnectionManager *conn)
{
	_conn = conn;
}
